//
//  InAppPayment.m
//  ImageRecognition
//
//  Created by yusaiyan on 2018/7/28.
//  Copyright © 2018年 QunYu. All rights reserved.
//

#import "InAppPayment.h"
#import <StoreKit/StoreKit.h>

@interface InAppPayment () <SKPaymentTransactionObserver, SKProductsRequestDelegate> {
    InAppPaymentSuccess _success;
    InAppPaymentFailed _failed;
    NSString *_productId;
}

@end

@implementation InAppPayment

static InAppPayment *_manager = nil;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc]init];
        [_manager addTransactionObserver];
    }) ;
    
    return _manager;
}

- (void)addTransactionObserver {
    // 4.设置支付服务
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)createPaymentWithPID:(NSString *)productId success:(InAppPaymentSuccess)success failed:(InAppPaymentFailed)failed  {
    _success = success;
    _failed = failed;
    _productId = productId;
    
    NSSet *set = [NSSet setWithArray:@[_productId]]; // 这个就是产品ID，在iTunes后台创建
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers: set];
    request.delegate = self; // 遵守SKProductsRequestDelegate代理
    [request start];
}

#pragma mark - SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *products = response.products; // 获取到的商品数组
    
    if (products.count == 0) {
        // 没有获取到
        // 代码到此，就是有商品了。这时就有两种操作，一种是向服务器验证购买凭证，获取订单字符串，发起购买；一种是直接拿商品ID发起购买。
        SKMutablePayment *mPayment = [[SKMutablePayment alloc] init];
        mPayment.productIdentifier = _productId; // 产品ID
        [[SKPaymentQueue defaultQueue] addPayment:mPayment]; // 调起支付界面，发起购买
    } else {
        SKProduct *p = nil;
        for (SKProduct *pro in products) {
            if ([pro.productIdentifier isEqualToString:_productId]) {
                p = pro;
            }
        }
        SKPayment *payment = [SKPayment paymentWithProduct:p];
        NSLog(@"发送购买请求");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

#pragma mark - SKPaymentTransactionObserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray*)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
            {
                NSLog(@"商品加入列表，正在购买中...");
                
            }   break;
            case SKPaymentTransactionStatePurchased: // 购买完成
            {
                NSLog(@"购买完成");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                [self completeTransaction:transaction];
            }   break;
            case SKPaymentTransactionStateFailed: // 交易失败
            {
                NSLog(@"交易失败");
                if (_failed) {
                    _failed(transaction.error);
                }
            }   break;
            case SKPaymentTransactionStateRestored: //已经购买过该商品
            {
                NSLog(@"已经购买过该商品");
            }   break;
            default:
                break;
        }
    }
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    // truely purchase IAP product for user
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    if (_success) {
        _success(receiptString);
    }
}

@end
